<template>
  <view class="mxio-scrollx-warpper">
    <scroll-view
      class="mxio-scrollx-box"
      :style="{
        background: `${scrollBackground}`,
      }"
      scroll-x="true"
      @scroll="scroll"
      scroll-left="0"
    >
      <!-- ref="scrollContainer" @mousedown="handleTouchStart"
      @mousemove="handleTouchMove" @mouseup="handleTouchEnd" -->
      <view
        class="mxio-scrollx-box-grid"
        :style="{
          gridTemplateColumns: `repeat(${propscolList},${scrollColumnWidth})`,
        }"
      >
        <view
          v-for="(item, index) in dataList"
          :key="index"
          class="mxio-scrollx-box-grid_item"
          @click.stop="scrollItemClick(item, index, dataList)"
        >
          <view
            v-if="item.bgColor"
            :style="{
              position: `absolute`,
              width: itemSize,
              height: itemSize,
              zIndex: `0`,
              background: `${item.bgColor}`,
              borderRadius: `${
                item.bgShape == 'circle'
                  ? '50%'
                  : item.bgShape == 'square'
                  ? '20rpx'
                  : ''
              }`,
            }"
          >
          </view>
          <slot name="icon" :iconItem="item" :props="$props" :index="index">
            <view
              class="__icon"
              :style="{
                width: itemSize,
                height: itemSize,
              }"
              v-if="item.iconType == 'font'"
            >
              <text
                class="meunfont meunfont-tabbar"
                :class="[item.icon]"
                :style="{
                  fontSize: item.iconSize || 50 + 'rpx',
                  lineHeight: item.iconSize || 50 + 'rpx',
                  color: item.iconColor || 'white',
                }"
              ></text>
            </view>
            <image
              v-else
              :src="getIcon(item.icon)"
              :mode="imgMode"
              class="mxio-scrollx-box-grid_img"
              :style="{
                width: itemSize,
                height: itemSize,
              }"
            >
            </image>
          </slot>
          <view class="mxio-scrollx-box-grid_txt">{{ item.label }}</view>
        </view>
      </view>
    </scroll-view>
    <view
      class="mxio-scrollx-bar-box"
      v-if="barShow"
      :style="{
        width: `${barWidthRpx}`,
        background: `${barBackground}`,
      }"
      @click.native.stop="scrollBarClick"
    >
      <view
        class="mxio-scrollx-bar-item"
        :style="{
          transform: `translateX(${scrollViewLeft}px)`,
        }"
      >
        <view
          class="mxio-scrollx-bar-item_H"
          :style="{
            width: `${barWidthHalfRpx}`,
            background: `${barColor}`,
          }"
        ></view>
      </view>
    </view>
  </view>
</template>
<script>
export default {
  name: "scroll-x-menu",
  props: {
    barWidth: {
      type: Number,
      default: 80,
    },
    scrollBackground: {
      type: String,
      default: "white",
    },
    barColor: {
      type: String,
      default: "#007AFF",
    },
    barBackground: {
      type: String,
      default: "#ccc",
    },
    barShow: {
      type: Boolean,
      default: true,
    },
    dataSource: {
      type: Array,
      default: () => [],
    },
    column: {
      type: Number,
      default: 5,
    },
    colList: {
      type: Number,
      default: 5,
    },
    imgMode: {
      type: String,
      default: "scaleToFill",
    },
    // 图片前缀
    iconPrePath: {
      type: String,
      default: "",
    },
    itemSize: {
      type: String,
      default: "70rpx",
    },
  },
  data() {
    return {
      scrollViewLeft: 0,
      scrollInnerWidth: 0,
      propscolList: 0,
      barWidthHalfCopy: 0,
      barWidthPx: 0,
      barWidthRpx: "0px",
      barWidthHalfRpx: "0px",
      scrollColumnWidth: "0px",
      propscolumn: 0,
      scroll_view_H: null,
      propsbarColor: "",
      propsbarBackground: "",
      dataList: [],
    };
  },
  watch: {
    dataSource: {
      immediate: true,
      deep: true,
      handler(val, old) {
        if (Array.isArray(val)) {
          this.dataList = Array.from(val).sort((a, b) => a.sort - b.sort) || [];
          // this.init();
        }
      },
    },
  },
  // #ifdef APP-PLUS
  // ps: 在 APP 端 cloumn 不生效， 暂未明白
  create() {
    this.init();
  },
  // #endif

  // #ifndef APP-PLUS
  mounted() {
    this.init();
  },
  // #endif
  computed: {
    getIcon() {
      return (icon) => {
        // 如果 icon 匹配到http标识，则直接返回
        if (icon.match(/^https?:/)) return icon;
        return this.iconPrePath + icon;
      };
    },
  },
  methods: {
    async init() {
      // 需要先排序一下，注意排序字段sort，升序，且
      this.dataList =
        Array.from(this.dataSource).sort(
          (a, b) => (a.sort || 0) - (b.sort || 0)
        ) || [];

      // bar宽度 2022-08-17 16:26:57
      this.barWidthPx = uni.upx2px(this.barWidth);
      this.barWidthHalfCopy = this.barWidthPx / 2;
      this.barWidthRpx = this.barWidthPx + "px";
      this.barWidthHalfRpx = this.barWidthHalfCopy + "px";

      // 列个数
      let dataSourceLen = this.dataSource.length;
      this.propscolList = 0;
      if (!dataSourceLen) {
        this.propscolList = this.colList;
      } else {
        this.propscolList =
          this.colList > dataSourceLen ? dataSourceLen : this.colList;
        // 最小列数
        if (this.propscolList < 4) {
          this.propscolList = 4;
        }
      }
      await this.scrollViewDOMCal();
    },
    scroll(e) {
      // console.log("scroll,e", e);
      let scrollLeft = e.detail.scrollLeft;
      let scrollWidth = e.detail.scrollWidth;
      let scrollItem = scrollWidth - this.scrollInnerWidth;
      let scrollItemCal = scrollLeft / scrollItem;
      let maxLeft = scrollItem;
      let nowLeft = scrollItemCal * this.barWidthHalfCopy;
      if (scrollLeft <= 0) nowLeft = 0;
      this.scrollViewLeft = nowLeft;
    },
    scrollViewDOM() {
      return new Promise((resolve) => {
        const query = uni.createSelectorQuery().in(this);
        query
          .select(".mxio-scrollx-box-grid")
          .boundingClientRect((data) => {
            resolve(data);
          })
          .exec();
      });
    },
    async scrollViewDOMCal() {
      let p = await this.scrollViewDOM();
      this.scrollInnerWidth = p.width;
      this.propscolumn = this.column <= 0 ? 5 : this.column;
      this.scrollColumnWidth = this.scrollInnerWidth / this.propscolumn + "px";
    },
    scrollItemClick(item, index, obj) {
      this.$emit("onItemClick", item, index, obj);
    },
    scrollBarClick(e) {
      // this.custmScrollLeft = ( this.scrollViewLeft  >= 0) ? 0 : 1000;
      this.propscolList =
        this.propscolList == this.colList ? this.column : this.colList; // ()this.colList
      // console.log("scrollBarClick,e", this.propscolList, this.colList);
    },
    // handleTouchStart(event) {
    //   console.log("handleTouchStart,e", event);
    //   this.isDragging = true;
    //   // this.startX = event.touches[0].clientX;
    //   this.startX = event.clientX;
    // },
    // handleTouchMove(event) {
    //   if (!this.isDragging) {
    //     return;
    //   }
    //   console.log("handleTouchMove,e", event);
    //   // this.currentX = event.touches[0].clientX;
    //   this.currentX = event.clientX;
    //   this.offset = this.currentX - this.startX;
    //   // console.log("this.$refs.scrollContainer", this.offset, this.$refs.scrollContainer);
    //   // this.$refs.scrollContainer.style.transform = `translateX(${this.offset}px)`;
    //   // this.$nextTick(() => {
    //   //   this.$refs.scrollContainer.scrollTo({
    //   //     left: this.offset,
    //   //     behavior: 'smooth', // 平滑滚动
    //   //   });
    //   // })
    // },
    // handleTouchEnd() {
    //   this.isDragging = false;
    //   console.log("handleTouchStart,e");
    // },
  },
};
</script>
<style lang="scss" scoped>
.mxio-scrollx-warpper {
  .mxio-scrollx-box {
    white-space: nowrap;

    ::v-deep.uni-scroll-view {
      &::-webkit-scrollbar {
        display: none;
      }
    }

    .mxio-scrollx-box-grid {
      display: grid;
      /** 默认值 */
      grid-template-columns: repeat(auto-fill, minmax(180rpx, 1fr));

      .mxio-scrollx-box-grid_item {
        display: flex;
        align-items: center;
        flex-direction: column;
        padding: 24rpx 0;
        font-size: 24rpx;
        overflow: hidden;

        .__icon {
          position: relative;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-bottom: 10rpx;
        }
      }

      .mxio-scrollx-box-grid_txt {
        color: #333;
      }

      .mxio-scrollx-box-grid_img {
        display: block;
        width: 60rpx;
        height: 60rpx;
        margin-bottom: 12rpx;
      }
    }
  }

  .mxio-scrollx-bar-box {
    height: 10rpx;
    margin: 10rpx auto;
    border-radius: 6rpx;

    .mxio-scrollx-bar-item {
      transition-property: transform;
      transition-delay: 0;
      transition-duration: 0.05s;
      transition-timing-function: linear;
      transform: translateX(0px);

      .mxio-scrollx-bar-item_H {
        height: 10rpx;
        border-radius: 6rpx;
      }
    }
  }
}
</style>
